#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <string.h>
#include <cJSON.h>
#include <math.h>
#include <time.h>
#define string (char*)

void error_handling(char *message);

int main(int argc,char **argv){

	/*int str_len;

	if(argc!=3){
		printf("Usage : %s <IP> <port>\n",argv[0] );
		exit(1);
	}

	sock = socket(PF_INET,SOCK_STREAM,0);
	if(sock == -1){
		error_handling("socket() error");
	}

	memset(&serv_addr,0,sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_addr.s_addr=inet_addr(argv[1]);
	serv_addr.sin_port=htons(atoi(argv[2]));

	if(connect(sock,(struct sockaddr*)&serv_addr,sizeof(serv_addr))==-1){
		error_handling("connect() errror!");
	}

	write(sock,message,sizeof(message));
	printf("%s\n",message );
	str_len = read(sock,message,sizeof(message));
	if(str_len==-1){
		error_handling("read() error!");
	}

	printf("message from server : %s \n",message);

	close(sock);*/

	FILE *file=fopen("../tables/FM1.json","r");
	if(file==NULL){
		error_handling("open is error \n");
	}
	printf("open is over\n");
	char JMsg[1024*60];
	char *Json=JMsg;
	while(fread(Json,1,10,file)){
		Json+=10;
	}
	printf("JMsg:%s\n",JMsg );
	fclose(file);
	cJSON *pJson = cJSON_Parse(JMsg);
	cJSON *pArray= cJSON_GetObjectItem(pJson,"tracks");
	int iCount = cJSON_GetArraySize(pArray);
	srand((int) time(0));
	int i = rand()%(iCount-1);
	printf("iCount = %d rand = %d i=%d\n ",iCount,rand(),i );
	cJSON* pItem = cJSON_GetArrayItem(pArray, i);
	char* title = cJSON_GetObjectItem(pItem, "title")->valuestring;
	char* uid = cJSON_GetObjectItem(pItem, "uid")->valuestring;
	char* play_url = cJSON_GetObjectItem(pItem, "play_url")->valuestring;
	printf("title = %s uid = %s play_url = %s\n",title,uid,play_url);
	return 0 ;
}

void error_handling(char *message){
	fputs(message,stderr);
	fputc('\n',stderr);
	exit(1);
}
